/**
 *  注册接口
 */

const router = require('express').Router()
const db = require('../../../dbconfig')

router.post('/register',(req,res) => {
    let user = req.query.username
    let password = req.query.password
    const userInfo = {user, avata: "default.jpg", name: "新用户",attention: 0, fans: 0, issue: 0, favorite: 0}
    
    let sql = 'insert into users (user, password) values (' + '"' + user+ '"' + ',' + '"' + password + '"' + ')'
    db.query(sql,(err,data)=>{
        if(err){
            // 我们在数据库中使用ALTER TABLE users ADD UNIQUE (user); 为user字段设置了唯一约束
            // 如果在插入数据前user会检察是否重复，是则抛出错误

            // console.log(err)
            res.send({status: 400, message: '该用户已被注册'})
        }else{
            let userId = data.insertId // 获取新插入的用户id
            const insertUserInfoSql = `INSERT INTO userinfo SET ?`
            db.query(insertUserInfoSql, { ...userInfo, id: userId }, (back) => {
                if (back.affectedRows != 1) {
                    res.send({status: 400, message: '注册失败'})
                } else {
                    res.send({status: 200, message: '注册成功'})
                }
            })
        }
    })
})

module.exports = router